package com.cjw.campus.core.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjw.campus.core.enums.ResponseCodeEnum;
import com.cjw.campus.core.result.ResponseResult;
import com.cjw.campus.system.entity.ForegroundUserTable;
import com.cjw.campus.system.service.IForegroundUserTableService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录Controller
 * @author xiefan
 */
@Slf4j
@RestController
@RequestMapping("/common/login")
@AllArgsConstructor
@Tag(name = "微信小程序登录管理")
public class LoginController {

    private final WxMaService wxMaService;

    private final IForegroundUserTableService foregroundUserTableService;

    @GetMapping("/getOpenIdByCode/{appid}/{code}")
    @Operation(summary = "根据code获取用户openid")
    public ResponseResult getOpenIdByCode(@PathVariable("appid") String appid,@PathVariable("code") String code) {
        // 判断传过来的code是否为空
        if (StrUtil.isBlank(code)) {
            return ResponseResult.error(ResponseCodeEnum.SELECT_FAIL);
        }
        // 判断appid是否合法
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
            // 根据code获取用户sessionInfo
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            // 先根据openid查询数据库是否存在该信息
            QueryWrapper<ForegroundUserTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ForegroundUserTable::getOpenId, session.getOpenid());
            ForegroundUserTable foregroundUser = foregroundUserTableService.getOne(queryWrapper);
            if (foregroundUser == null) {
                foregroundUser = new ForegroundUserTable();
                foregroundUser.setOpenId(session.getOpenid());
                foregroundUserTableService.save(foregroundUser);
            }
            // 执行登录功能
            // 签发令牌 =》 JWT   JSON WEB Token
            // 先将数据存放到map中
            Map<String, Object> map = new HashMap<>();
            map.put("foregroundUser", foregroundUser);
            // 当前时间
            map.put("currentTime", System.currentTimeMillis());
//            生成token
            String token = JWTUtil.createToken(map, "1234".getBytes());
            map.put("token", token);
            System.out.println(token);
            return ResponseResult.ok(ResponseCodeEnum.SELECT_SUCCESS, map);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return ResponseResult.error(ResponseCodeEnum.SELECT_FAIL);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取微信小程序用户信息")
    public ResponseResult getUserInfo(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return ResponseResult.error(ResponseCodeEnum.SELECT_FAIL);
        }
        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return ResponseResult.ok(ResponseCodeEnum.SELECT_SUCCESS, userInfo);
    }

    @GetMapping("/getUserPhone")
    @Operation(summary = "获取微信小程序用户手机号码")
    public ResponseResult getUserPhone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return ResponseResult.error(ResponseCodeEnum.SELECT_FAIL);
        }
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return ResponseResult.ok(ResponseCodeEnum.SELECT_SUCCESS, phoneNoInfo);
    }


}
